package org.vacoor.nothing.security.nls.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vacoor.nothing.security.nls.Translator;

import java.util.Locale;
import java.util.Properties;

/**
 */
public abstract class TranslatorSupport implements Translator {
    protected final Logger LOG = LoggerFactory.getLogger(getClass());

    @Override
    public boolean accepts(Locale from, Locale to) {
        return from.equals(to);
    }

    @Override
    public String translate(String text, Locale from, Locale to) {
        return translate(text, from, to, null);
    }

    @Override
    public String translate(String text, Locale from, Locale to, Properties props) {
        return from.equals(to) ? text : (accepts(from, to) ? doTranslate(text, from, to, getProperties(props)) : null);
    }

    protected abstract String doTranslate(String text, Locale from, Locale to, Properties props);

    protected Properties getProperties(Properties props) {
        return null != props ? props : new Properties(System.getProperties());
    }

    /**
     * 将 Locale 转换为中划线写法 zh-CN (java 默认下划线 zh_CN)
     *
     * @param loc
     * @return
     */
    protected String toDash(Locale loc) {
        String language = loc.getLanguage();
        String country = loc.getCountry();
        return null != country && !"".equals(country) ? language + "-" + country : language;
    }
}
